﻿using System.Collections;
using System.Windows;
using System.Windows.Controls;

namespace JustinAngel.UnitedNationsNews.Pages.Article
{
    public static class ListBoxExtensions
    {
        #region NonVirtualizedItemsSource (Attached DependencyProperty)

        public static readonly DependencyProperty NonVirtualizedItemsSourceProperty =
            DependencyProperty.RegisterAttached("NonVirtualizedItemsSource", typeof(IEnumerable), typeof(ListBoxExtensions), new PropertyMetadata(new PropertyChangedCallback(OnNonVirtualizedItemsSourceChanged)));

        public static void SetNonVirtualizedItemsSource(ListBox o, IEnumerable value)
        {
            o.SetValue(NonVirtualizedItemsSourceProperty, value);
        }

        public static double GetNonVirtualizedItemsSource(ListBox o)
        {
            return (double)o.GetValue(NonVirtualizedItemsSourceProperty);
        }

        private static void OnNonVirtualizedItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ListBox sender = (ListBox) d;
            IEnumerable value = (IEnumerable) e.NewValue;

            CreateNonVirtualizedItemsBasedOn(sender, sender.ItemTemplate, value);
        }

        private static void CreateNonVirtualizedItemsBasedOn(ListBox listBox, DataTemplate itemTemplate, IEnumerable itemSource)
        {
            foreach (var item in itemSource)
            {
                ListBoxItem container = new ListBoxItem();
                container.Content = itemTemplate.LoadContent();
                container.DataContext = item;
                listBox.Items.Add(container);
            }
        }

        #endregion
    }
}